package com.yebxxx.Utils;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.yebxxx.server.pojo.Employee;
import com.yebxxx.server.pojo.MailConstance;
import com.yebxxx.server.pojo.MailLog;
import com.yebxxx.server.service.IEmployeeService;
import com.yebxxx.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息定时器
 */
@Component
public class MailTask {
    /**
     * 邮件发送 10s一次
     */
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0).lt("tryTime", LocalDateTime.now()));
         //重试次数超过三次，状态为失败
        list.forEach(mailLog -> {
            if(3<=mailLog.getCount()){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",2).eq("msgId",mailLog.getMsgId()));
            }
            mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1).set("updateTime",LocalDateTime.now()).
                    set("tryTime",LocalDateTime.now().plusMinutes(MailConstance.MSG_TIMEOUT)).eq("msgId",mailLog.getMsgId()));
            
            Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
            //发送消息
            rabbitTemplate.convertAndSend(MailConstance.MAIL_EXCHANGE,MailConstance.MAIL_ROUTEING_KEY_NAME
            ,employee,new CorrelationData(mailLog.getMsgId()));
        });
    }
}
